package engine.render;

import engine.render.buffer.TriBuffer;
import engine.render.type.Tri;
import java.util.Iterator;
import java.util.LinkedList;

public class RenderScene 
{
    
    private final int kMaxDynamicTris;
    
    private Tri[] renderStatic;
    public Tri[] getStaticRender() 
    {
        return renderStatic;
    }
    
    private Tri[] renderDynamic;
    private LinkedList<Tri[]> preRenderStatic;
    private LinkedList<Tri[]> preRenderDyn;
    private int nTrisStat;
    private int nTrisDyn;
    private boolean addedStatic;
    
    protected float time;
    
    public RenderScene(int maxDynamicTris) 
    {
        kMaxDynamicTris = maxDynamicTris;
        preRenderDyn = new LinkedList<Tri[]>();
        renderDynamic = new Tri[kMaxDynamicTris];
        nTrisStat = 0;
        nTrisDyn = 0;
        preRenderStatic = new LinkedList<Tri[]>();
        addedStatic = false;
    }
    
    protected void addDynamicTris() 
    {
    }
    
    protected void finishAddStaticTris() 
    {
        renderStatic = new Tri[nTrisStat];
        copyLListToArray(preRenderStatic, renderStatic);
        addedStatic = true;
    }
    
    public void update(TriBuffer dim3, float timeCycle) 
    {
        time += timeCycle;
        addDynamicTris();
        copyLListToArray(preRenderDyn, renderDynamic);
        dim3.triangles(getStaticRender());
        dim3.triangles(getDynamicRender());
    }
    
    protected void trisStatic(Tri[] tris) 
    {
        if (!addedStatic && tris != null) 
        {
            preRenderStatic.addLast(tris);
            nTrisStat += tris.length;
        }
    }
    
    protected void trisDynamic(Tri[] tris) 
    {
        if (tris != null) 
        {
            preRenderDyn.addLast(tris);
            nTrisDyn += tris.length;
        }
    }
    
    public Tri[] getDynamicRender() 
    {
        Tri[] renderDynClone = renderDynamic.clone();
        clearDynamicTris();
        return renderDynClone;
//        preRenderDyn.clear();
//        nTrisDyn = 0;
//        return renderDynamic;
    }
    
    private void clearDynamicTris() 
    {
        preRenderDyn.clear();
        for (int i = 0; i < nTrisDyn; i++) 
        {
            renderDynamic[i] = null;
        }
        nTrisDyn = 0;
    }
    
    private void copyLListToArray(LinkedList<Tri[]> list, Tri[] array) 
    {
        int j = 0;
        Iterator iter = list.iterator();
        Tri[] localArray;
        while (iter.hasNext()) 
        {
            localArray = (Tri[]) iter.next();
            for (int i = 0; i < localArray.length; i++) 
            {
                array[j++] = localArray[i];
            }
        }
    }
    
}
